//推荐列表+购物车
(function($) {
	$('.products_list').hover(function() {
		$('.products_list #left,#right').show();
	}, function() {
		$('.products_list #left,#right').hide();
	});
	var $len = $('.products li').length;
	var $len2 = $('.products_btn li').length;
	var $w = $('.products li:first').outerWidth();
	var $w2 = $('.products_list').width();
	var $clone1 = $('.products li').clone();
	var $clone2 = $clone1.clone();
	$('.products').append($clone1);
	$('.products').append($clone2);
	
	$('.products').css({
		'width': 999999
	});
	var $index = 0;
	$('.products_btn li').on('mouseover', function() {
		$index = $(this).index();
		tab();
	});

	function tab() {
		$('.products_btn li').eq($index).addClass('active').siblings().removeClass();
		$('.products').stop(true, true).animate({
			left: -$w2 * $index
		}, 'fast');
	}
	$('.products_list #right').on('click', function() {
		$index++;
		if($index > $len2 - 1) {
			$index = 0;
		}
		tab();
	});
	$('.products_list #left').on('click', function() {
		$index--;
		if($index < 0) {
			$index = $len2 - 1;
		}
		tab();
	});
	$.ajax({
			type: "get",
			url: "../php/cart.php",
			async: true
		})
		.done(function(data) {
			var data = JSON.parse(data);
			var html = '';
			for(var i = 0; i < data.length; i++) {
				html +=
					'<li><a id="product_img" href="##"><span></span><img src=' + data[i].img_url + ' /></a>' +
					'<a id="product_title" href="##">' + data[i].title + '' + data[i].description + '</a>' +
					'<p id="product_price">' + data[i].price + '</p>' +
					'<button sid=' + i + '>加入购物车</button>' +
					'</li>';
			}
			$('.products').html(html);

			//购物车
			var arrindex = [];
			var arrnum = [];

			function toArray() {
				if(getCookie('cartindex')) {
					arrindex = getCookie('cartindex').split(',');
				}
				if(getCookie('cartnum')) {
					arrnum = getCookie('cartnum').split(',');
				}
			}

			function existArray(value, arr) {
				for(var i = 0; i < arr.length; i++) {
					if(arr[i] == value) {
						return true;
					}
				}
				return false;
			}
			
			var num = 0;
			$('.products button').on('click', function() {
				num = $(this).attr('sid');
				toArray();
				
				//读取cart cookie
				var cart_str = getCookie('cart');
				if(cart_str != null) {
					//string转json
					//console.log("cart: "+unescape(cart_str));
					var cartInfo = JSON.parse(unescape(cart_str));
					var is_exit = false;
					for(var i = 0; i < cartInfo.length; i++) {
						var product = cartInfo[i];						
						//判断购物车内是否已存在
						if(product.name == num) {
							cartInfo[i].count++;
							//存在标记更改
							is_exit = true;
							
							$('#cartTable tr').each(function(i) {
								if($(this).attr('trindex') == num) {
									//var $number = parseInt($(this).find('td').eq(5).html());
									//$number++;
									$(this).find('td').eq(5).html(cartInfo[i].count);
									var $total1 = cartInfo[i].count * parseFloat(data[num].price.substring(1));
									$(this).find('td').eq(7).html('¥' + $total1 + '');
								}
							});
						}							
					}
					if(!is_exit) {
						var p = {}
						p.name = num;
						p.count = 1;
						cartInfo.push(p);
						createcart(num, 1);
						$('.blanks').hide();
					}
				}else {
					var cartInfo = Array();
					var p = {}
					p.name = num;
					p.count = 1;
					cartInfo.push(p);
					createcart(num, 1);
					$('.blanks').hide();
				}
				console.log(JSON.stringify(cartInfo));
				//序列化存入cookie
				$.cookie('cart', escape(JSON.stringify(cartInfo)), { expires: 7, path: '/' });
				//addCookie('cart', cartInfo, 7);
				/*
				if(existArray(num, cartInfo)) {
					$('#cartTable tr').each(function(i) {
						if($(this).attr('trindex') == num) {
							var $number = parseInt($(this).find('td').eq(5).html());
							$number++;
							$(this).find('td').eq(5).html($number);
							arrnum[i] = $number;
							addCookie('cartnum', arrnum.toString(), 7);
							var $total1 = arrnum[i] * parseFloat(data[num].price.substring(1));
							$(this).find('td').eq(7).html('¥' + $total1 + '');
						}
					});

				} else {
					arrindex.push(num);
					arrnum.push(1);
					addCookie('cartindex', arrindex.toString(), 7);
					addCookie('cartnum', arrnum.toString(), 7);
					createcart(num, 1);
					$('.blanks').hide();
				}
				*/
				/*
				if(existArray(num, arrindex)) {
					$('#cartTable tr').each(function(i) {
						if($(this).attr('trindex') == num) {
							var $number = parseInt($(this).find('td').eq(5).html());
							$number++;
							$(this).find('td').eq(5).html($number);
							arrnum[i] = $number;
							addCookie('cartnum', arrnum.toString(), 7);
							var $total1 = arrnum[i] * parseFloat(data[num].price.substring(1));
							$(this).find('td').eq(7).html('¥' + $total1 + '');
						}
					});

				} else {
					arrindex.push(num);
					arrnum.push(1);
					addCookie('cartindex', arrindex.toString(), 7);
					addCookie('cartnum', arrnum.toString(), 7);
					createcart(num, 1);
					$('.blanks').hide();
				}
				*/
			});
			

			function createcart(now, count) {
				var str = '';
				for(var i = 0; i < data.length; i++) {
					if(i == now) {
						str +=
							'<tr trindex=' + now + '>' +
							'<td style="width:88px;height:100px;"><input class="ck" type="checkbox" checked="checked" /></td>' +
							'<td width="95" height="100"><a href="##"><img src=' + data[i].img_url + ' /></a></td>' +
							'<td width="150" height="100"><a href="##">' + data[i].title + '</td>' +
							'<td width="192" height="100"><a href="##">' + data[i].description + '</td>' +
							'<td width="140" height="100"><a href="##">' + data[i].price + '</td>' +
							'<td width="112" height="100">' + count + '</td>' +
							'<td width="167" height="100"></td>' +
							'<td width="140" height="100">' + data[i].price + '</td>' +
							'<td width="100" height="100"><a x=' + i + ' class="remove"  href="javascript:;">删除</a></td>' +
							'</tr>';
					}
				}
				$('#cartTable').get(0).innerHTML += str;
			}

			//读取cart cookie
			var cart_str = getCookie('cart');
			if(cart_str != null) {
				//string转json
				//console.log("cart: "+unescape(cart_str));
				var cartInfo = JSON.parse(unescape(cart_str));
				for(var i = 0; i < cartInfo.length; i++) {
					createcart(cartInfo[i].name, cartInfo[i].count);
					var $total = cartInfo[i].count * parseFloat(data[cartInfo[i].name].price.substring(1));
					$('#cartTable tr').eq(i).find('td').eq(7).html('¥' + $total + '');							
				}
				$('.blanks').hide();
			} else {
				$('.blanks').show();
			}
			
			/*
			if(getCookie('cartindex')) {
				var newarrindex = getCookie('cartindex').split(',');
				var newarrnum = getCookie('cartnum').split(',');
				for(var i = 0; i < newarrindex.length; i++) {
					createcart(newarrindex[i], newarrnum[i]);
					var $total = newarrnum[i] * parseFloat(data[newarrindex[i]].price.substring(1));
					$('#cartTable tr').eq(i).find('td').eq(7).html('¥' + $total + '');
				}
				$('.blanks').hide();
			} else {
				$('.blanks').show();
			}
			*/
			//删除购物车里面内容
			
			$("#cart_body").on('click', '.remove', function() {
				var nowindex = $(this).attr('x');
				$(this).parent().parent().remove();
				
				var cart_str = getCookie('cart');
				var cartInfo = JSON.parse(unescape(cart_str));
				console.log(cartInfo);
				var new_cart = Array();
				for(var i = 0; i < cartInfo.length; i++) {
					var product = cartInfo[i];
					if(product.name != nowindex) {
						new_cart.push(product);
					}							
				}
				
				console.log(JSON.stringify(new_cart));
				if(new_cart.length > 0) {
					//序列化存入cookie
					$.cookie('cart', escape(JSON.stringify(new_cart)), { expires: 7, path: '/' });
				} else {
					//序列化存入cookie
					$.cookie('cart', null, { expires: -1, path: '/' });
				}
				
			});
			/*
			$('.remove').on('click', function() {
				var nowindex = $(this).attr('x');
				$(this).parent().parent().remove();
				
				var arr1 = [];
				var arr2 = [];
				arr1 = getCookie('cartindex').split(',');
				arr2 = getCookie('cartnum').split(',');
				console.log(arr1);
				console.log(arr2);
				delCookie('cartindex', arr1[nowindex]);
				delCookie('cartnum', arr2[nowindex]);
			});*/

			//购物车全选按钮
			$('#product_checkall').on('click', function() {
				if($(this).prop('checked')) {
					$('#cartTable .ck').prop('checked', true);
					console.log()
				} else {
					$('#cartTable .ck').prop('checked', false);
				}
			});
			$('#cartTable .ck').on('click', function() {
				var $len = $('#cartTable .ck').length;
				var $len2 = $('#cartTable input:checked').not('#product_checkall').length;
				if($len2 == $len) {
					$('#product_checkall').prop('checked', true);
				} else {
					$('#product_checkall').prop('checked', false);
				}
			});
		})
		.fail(function(xhr, err) {
			console.log(xhr, err);
		});

})(jQuery);